/*
 * @copyright 2010 Gerald Jacobson
 * @license GNU General Public License
 * 
 * This file is part of Descent Assistant.
 *
 * Descent Assistant is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Descent Assistant is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Descent Assistant.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.amphiprion.descenttool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.amphiprion.descenttool.control.ControlerState;
import org.amphiprion.descenttool.control.TouchControler;
import org.amphiprion.descenttool.entity.Monster;
import org.amphiprion.descenttool.util.ApplicationConstants;
import org.amphiprion.descenttool.util.BitmapUtil;
import org.amphiprion.descenttool.util.PreferenceUtil;
import org.amphiprion.descenttool.view.EncounterView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;

public class Home extends Activity {
	private volatile boolean running = false;
	private EncounterView view;

	public Home() {
		super();
	}

	private void init() {
		if (PreferenceUtil.getInt(PreferenceUtil.Preference.ENCOUNTER_MODE, -1) == -1) {
			displayPreferences();
		}
		extractXMLs(false);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		init();

		view = new EncounterView(this);
		setContentView(view);

		final TouchControler tc = new TouchControler(view);

		new Thread(new Runnable() {

			@Override
			public void run() {
				running = true;
				long timer = System.currentTimeMillis();
				long drawtimer = System.currentTimeMillis();
				while (running) {
					if (!view.drawing) {
						ControlerState state = tc.getControlerState();
						long newtimer = System.currentTimeMillis();
						view.onInput(state, newtimer - timer);
						timer = newtimer;
						if (newtimer - drawtimer >= 40) {
							drawtimer = newtimer;
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									view.invalidate();
								}
							});
						}
					}
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
					}
				}
			}
		}).start();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		view.saveViewData(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		view.restoreViewData(savedInstanceState);
	}

	@Override
	protected void onDestroy() {
		running = false;
		BitmapUtil.clearCache();
		super.onDestroy();
	}

	public void addMonsterRequested() {
		Intent i = new Intent(this, ChooseMonster.class);
		startActivityForResult(i, ApplicationConstants.RESULT_ACTIVITY_CHOOSE_MONSTER);
	}

	public static boolean extractXMLs(boolean allowOverride) {
		boolean result = true;
		try {
			File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY);
			f.mkdir();

			f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/monsters.xml");
			if (!f.exists() || allowOverride) {
				byte[] b = new byte[4096];
				InputStream is = Home.class.getResourceAsStream("/monsters.xml");
				FileOutputStream fos = new FileOutputStream(f);
				int len = 0;
				while ((len = is.read(b)) > 0) {
					fos.write(b, 0, len);
				}
				fos.close();
				is.close();
			}
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "Monsters file dump", e);
			result = false;
		}

		try {
			File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/definition.xml");
			if (!f.exists() || allowOverride) {
				byte[] b = new byte[4096];
				InputStream is = Home.class.getResourceAsStream("/definition.xml");
				FileOutputStream fos = new FileOutputStream(f);
				int len = 0;
				while ((len = is.read(b)) > 0) {
					fos.write(b, 0, len);
				}
				fos.close();
				is.close();
			}
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "Definition file dump", e);
			result = false;
		}
		return result;
	}

	public void displayPreferences() {
		Intent i = new Intent(this, PreferencesActivity.class);
		startActivity(i);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == ApplicationConstants.RESULT_ACTIVITY_CHOOSE_MONSTER) {
				List<Monster> selectedMonsters = (List<Monster>) data.getSerializableExtra("MONSTERS");
				for (Monster m : selectedMonsters) {
					view.addMonster(m);
				}
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getResources().getString(R.string.stop_message));
			builder.setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					finish();
				}
			});
			builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
				}
			});
			AlertDialog alert = builder.create();
			alert.show();

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}